<template>
  <div class="editor_box">
    <Toolbar
      class="editor_box_toolber"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
    />
    <Editor
      class="editor_box_textarea"
      :style="getStyle"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      @onChange="handleChange"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
  import { defineProps, defineEmits } from 'vue';
  import '@wangeditor/editor/dist/css/style.css'; // 引入 css
  import {
    onBeforeUnmount,
    ref,
    shallowRef,
    getCurrentInstance,
    computed,
  } from 'vue';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { putProgress } from '@/utils/oss.js';
  import { Message } from '@arco-design/web-vue';

  const emit = defineEmits(['contentChange']);

  const props = defineProps({
    content: String,
    height: Number,
    type: String,
  });
  const getStyle = computed(() => {
    return {
      height: props.height
        ? props.height + 'px !important'
        : '300px !important',
    };
  });

  const { proxy } = getCurrentInstance();
  const mainkey = window.config.VUE_APP_BASE_KEY;
  // 编辑器实例，必须用 shallowRef ，重要！
  const editorRef = shallowRef();
  // 内容 HTML
  const valueHtml = ref(props.content);
  // 编辑器配置
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        async customUpload(file, insertFn) {
          // JS 语法
          if (
            file.type != 'image/png' &&
            file.type != 'image/jpg' &&
            file.type != 'image/jpeg'
          ) {
            Message.error('请上传jpg或png格式的图片！');
            return;
          }
          const key = `${mainkey}/editor/images/${file.name}`;
          putProgress(key, file).then((res) => {
            let url = '';
            if (res && res.data && res.data.code == 200) {
              url = proxy.baseurl + res.data.data;
            } else {
              url = proxy.baseurl + key;
            }
            insertFn(url, '', url);
          });
        },
      },
      uploadVideo: {
        async customUpload(file, insertFn) {
          // JS 语法
          if (file.type != 'video/mp4') {
            Message.error('请上传mp4格式的图片！');
            return;
          }
          const key = `${mainkey}/editor/videos/${file.name}`;
          putProgress(key, file).then((res) => {
            let url = '';
            if (res && res.data && res.data.code == 200) {
              url = proxy.baseurl + res.data.data;
            } else {
              url = proxy.baseurl + key;
            }
            insertFn(url, '');
          });
        },
      },
    },
  };

  // 工具栏配置
  let toolbarConfig;
  if (props.type == 'simpleTopic') {
    toolbarConfig = {
      toolbarKeys: [],
      insertKeys: {
        index: 0, // 插入的位置，基于当前的 toolbarKeys
        keys: ['uploadImage', 'uploadVideo'],
      },
    };
  } else {
    toolbarConfig = {
      excludeKeys: ['group-image', 'group-video', 'fullScreen'],
      insertKeys: {
        index: 20, // 插入的位置，基于当前的 toolbarKeys
        keys: ['uploadImage', 'uploadVideo'],
      },
    };
  }

  // 编辑器回调函数
  const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
  };
  const handleChange = (editor) => {
    var data = {
      text: getText(),
      html: getHtml(),
    };
    emit('contentChange', data);
  };

  // 及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    // 销毁，并移除 editor
    editor.destroy();
  });

  const getText = () => {
    const editor = editorRef.value;
    if (editor == null) return;
    return editor.getText();
  };

  const getHtml = () => {
    const editor = editorRef.value;
    if (editor == null) return;
    return editor.getHtml();
  };
</script>

<style type="text/css" scoped="scoped">
  .editor_box {
    border: 1px solid #ccc;
    width: 100%;
  }

  .editor_box_toolber {
    border-bottom: 1px solid #ccc;
  }

  .editor_box_textarea {
    width: 100%;
  }
</style>
